/**
 * All rights Reserved, Designed By 姑苏区政府大数据中心
 *
 * @Copyright: 2019 姑苏区政府大数据中心. All rights reserved.
 * 注意：本内容仅限于姑苏区政府大数据中心内部传阅，禁止外泄以及用于其他的商业目
 */
package com.acp.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Title: CorsFilter.java
 * @Package com.acp.util
 * @Description: 跨域处理类
 * @author: 宁晶晶
 * @date: 2019/2/22 13:46
 */
@Component
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 跨域处理器
     *
     * @param req   请求
     * @param res   返回
     * @param chain 处理器
     * @throws IOException      异常
     * @throws ServletException 异常
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            String token = request.getHeader("token");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, Authorization, token");
            Claims claims = Jwts.parser().setSigningKey("itcast").parseClaimsJws(token).getBody();
            System.out.println(claims);
            chain.doFilter(req, res);
        } catch (Exception ex) {
            String str = "无权限调用。";
            byte[] srtbyte = str.getBytes("GB2312");
            //二进制48对应的名称为0
            res.getOutputStream().write(srtbyte);
            res.getOutputStream().flush();
            res.getOutputStream().close();
//          res.setContentType("charset=GBK");
        }
    }

    @Override
    public void destroy() {

    }
}
